package com.dianrui.fmi.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.dianrui.fmi.R;
import com.dianrui.fmi.adapter.SearchAdapter;
import com.dianrui.fmi.adapter.SearchLogAdapter;
import com.dianrui.fmi.bean.Search;
import com.dianrui.fmi.bean.SearchKeywords;
import com.dianrui.fmi.util.OkHttpUtils;
import com.dianrui.fmi.util.StringUtils;
import com.dianrui.fmi.util.Url;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * SearchActivity
 */

public class SearchActivity extends BaseActivity {
    private SearchAdapter searchAdapter;
    private SearchLogAdapter searchLogAdapter;
    private List<Search> mSearchList = new ArrayList<>();
    private List<SearchKeywords> mKeywordList = new ArrayList<>();

    @BindView(R.id.history_layout)
    LinearLayout historyLayout;
    @BindView(R.id.listview)
    ListView listview;
    @BindView(R.id.search_log_listview)
    GridView searchLogListview;
    @BindView(R.id.search_edit)
    EditText editSearch;
    @BindView(R.id.del_search_img)
    ImageView delSearchImg;
    @BindView(R.id.emptyView)
    LinearLayout emptyView;



    @Override
    public int getContentViewId() {
        return R.layout.activity_search;
    }

    @Override
    public void initView() {
        searchAdapter = new SearchAdapter(SearchActivity.this, mSearchList);
        listview.setAdapter(searchAdapter);
        getSearchLogList();
        editSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    delSearchImg.setVisibility(View.VISIBLE);
                } else {
                    delSearchImg.setVisibility(View.GONE);
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                    }
                    historyLayout.setVisibility(View.VISIBLE);
                    searchLogListview.setVisibility(View.VISIBLE);
                    listview.setVisibility(View.GONE);
                    getSearchLogList();
                    emptyView.setVisibility(View.GONE);
                }
            }
        });
        editSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {//软盘搜索键
                    //点击搜索要做的操作
                    searchLogListview.setVisibility(View.GONE);
                    listview.setVisibility(View.VISIBLE);
                    getSaveSearchResult();
                    goSearch();
                }
                return false;
            }
        });

        searchAdapter.setOnButtonClickListener(new SearchAdapter.SearchClickListener() {
            @Override
            public void onRegularClick(long tick, String name, String symbold, String type, String symbol, String fullsymbol, String price, String high, String low, String open, String zf, String yc, String buy1, String buy2, String position, String servicecharge, String zc) {
                Intent intent = new Intent(SearchActivity.this, KLineActivity.class);
                Bundle bundle = new Bundle();
                bundle.putLong("tick", tick);
                bundle.putString("symbold", symbold);
                bundle.putString("name", name);
                bundle.putString("type", type);
                bundle.putString("symbol", symbol);
                bundle.putString("open", open);
                bundle.putString("high", high);
                bundle.putString("low", low);
                bundle.putString("fullsymbol", fullsymbol);
                bundle.putString("price", price);
                bundle.putString("zf", zf);
                bundle.putString("zc", zc);
                bundle.putString("yc", yc);
                bundle.putString("buy1", buy1);
                bundle.putString("buy2", buy2);
                bundle.putString("position", position);
                bundle.putString("servicecharge", servicecharge);
                intent.putExtras(bundle);
                startActivity(intent);
            }

        });

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    //开始搜索
    private void goSearch() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("keywords", editSearch.getText().toString().trim());
        OkHttpUtils.getInstance().postWithMemberToken(Url.MAIN_SEARCH, jsonObject.toString(),  new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                if (mSearchList != null) {
                                    mSearchList.clear();
                                }
                                JSONArray data = jsonObject.optJSONArray("data");
                                if (data.length() > 0) {
                                    for (int i = 0; i < data.length(); i++) {
                                        Search search = new Search();
                                        search.symbols_id = data.optJSONObject(i).optString("symbols_id");
                                        search.full_symbol = data.optJSONObject(i).optString("full_symbol");
                                        search.symbol = data.optJSONObject(i).optString("symbol");
                                        search.name = data.optJSONObject(i).optString("name");
                                        search.type = data.optJSONObject(i).optString("type");
                                        search.market = data.optJSONObject(i).optString("market");
                                        search.tick = data.optJSONObject(i).optLong("tick");
                                        search.i = data.optJSONObject(i).optString("i");
                                        search.itd = data.optJSONObject(i).optString("itd");
                                        search.price = data.optJSONObject(i).optString("price");
                                        search.o = data.optJSONObject(i).optString("o");
                                        search.h = data.optJSONObject(i).optString("h");
                                        search.l = data.optJSONObject(i).optString("l");
                                        search.yc = data.optJSONObject(i).optString("yc");
                                        search.v = data.optJSONObject(i).optString("v");
                                        search.zf = data.optJSONObject(i).optString("zf");
                                        search.zd = data.optJSONObject(i).optString("zd");
                                        search.buy1 = data.optJSONObject(i).optString("buy1");
                                        search.buy2 = data.optJSONObject(i).optString("buy2");
                                        search.position = data.optJSONObject(i).optString("position");
                                        search.service_charge = data.optJSONObject(i).optString("service_charge");
                                        mSearchList.add(search);
                                    }
                                    if (searchAdapter != null) {
                                        searchAdapter.refresh(mSearchList);
                                    }
                                    searchLogListview.setVisibility(View.GONE);
                                    listview.setVisibility(View.VISIBLE);
                                    emptyView.setVisibility(View.GONE);
                                }else {
                                    searchLogListview.setVisibility(View.GONE);
                                    listview.setVisibility(View.GONE);
                                    emptyView.setVisibility(View.VISIBLE);
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                }
            }
        });
    }


    private void getSearchLogList() {
        OkHttpUtils.getInstance().postWithMemberToken(Url.MY_SEARCH, "", new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                if (mKeywordList != null) {
                                    mKeywordList.clear();
                                }
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        SearchKeywords searchKeywords=new SearchKeywords();
                                        searchKeywords.keywords=jsonArray.optJSONObject(i).optString("keywords");
                                        mKeywordList.add(searchKeywords);
                                    }
                                    searchLogAdapter = new SearchLogAdapter(SearchActivity.this, mKeywordList);
                                    searchLogListview.setAdapter(searchLogAdapter);
                                    searchLogListview.setVisibility(View.VISIBLE);
                                    listview.setVisibility(View.GONE);
                                    historyLayout.setVisibility(View.VISIBLE);

                                }else {
                                    listview.setVisibility(View.GONE);
                                    searchLogListview.setVisibility(View.VISIBLE);
                                    historyLayout.setVisibility(View.GONE);
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }


    //添加搜索记录
    private void getSaveSearchResult() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("keywords", editSearch.getText().toString().trim());
        OkHttpUtils.getInstance().postWithMemberToken(Url.SAVE_SEARCH, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if ("1000".equals(jsonObject.optString("status"))) {

                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                }
            }
        });

    }

    //删除搜索记录
    private void SearchResultDelete() {
        OkHttpUtils.getInstance().postWithMemberToken(Url.DEL_SEARCH, "",new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                if (mKeywordList != null) {
                                    mKeywordList.clear();
                                }
                                if (mSearchList != null) {
                                    mSearchList.clear();
                                }
                                getSearchLogList();
                                historyLayout.setVisibility(View.GONE);
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                }
            }
        });

    }


    @OnClick({R.id.del_search_img, R.id.cancel, R.id.search_record_del})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.del_search_img:
                editSearch.setText("");
                historyLayout.setVisibility(View.VISIBLE);
                searchLogListview.setVisibility(View.VISIBLE);
                listview.setVisibility(View.GONE);
                getSearchLogList();
                emptyView.setVisibility(View.GONE);
                break;
            case R.id.cancel:
                finish();
                break;

            case R.id.search_record_del:
                SearchResultDelete();
                break;
            default:
                break;
        }
    }
}
